package com.geek.novel.network

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.geek.novel.common.Constant
import com.geek.novel.utils.SPUtil
import com.geek.novel.utils.CommUtil
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException


/**
 *
 * Created by lfp on 2017/10/13.
 */
class TokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain?): Response {
        val request = chain?.request()
        val response = chain?.proceed(request!!)

        if (response?.let { isTokenExpired(it) }!!) {//根据和服务端的约定判断token过期
            //同步请求方式，获取最新的Token
            val newSession = getNewToken()
            //使用新的Token，创建新的请求
            val newRequest = chain.request()
                    .newBuilder()
                    .header("clientkey", newSession)
                    .build()
            //重新请求
            return chain.proceed(newRequest)
        }
        return response
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private fun isTokenExpired(response: Response): Boolean = response.code() == 401

    val map: HashMap<String, String> = HashMap()
    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */
    @Throws(IOException::class)
    private fun getNewToken(): String {
        // 通过一个特定的接口获取新的token，此处要用到同步的retrofit请求
        map.clear()
		map["clientid"] = Constant.CLIENT_ID
		map["account"] = CommUtil.account
		map["refreshkey"] = SPUtil[Constant.SP_refresh_key, "", SPUtil.usrInfo] as String
        val response = HttpReq.getData("services/open/clientPublicService/refreshClientToken", map)

        val jsonOb = JSON.parse(response)
        val jsonObs: JSONObject = JSON.parse(jsonOb as String) as JSONObject

        if (jsonObs.containsKey("clientkey"))
            SPUtil.put(Constant.SP_TOKEN, jsonObs.containsKey("clientkey"), SPUtil.usrInfo)

        if (jsonObs.containsKey("refreshkey")) {
            SPUtil.put(Constant.SP_refresh_key, jsonObs.getString("refreshkey"), SPUtil.usrInfo)
        }
        if (jsonObs.containsKey("exptime")) {
            SPUtil.put(Constant.SP_exp_time, jsonObs.getString("exptime"), SPUtil.usrInfo)
        }
        return jsonObs.getString("refreshkey")
    }


}